package com.wangyk.gateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import com.wangyk.gateway.exception.RateLimitException;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

/**
 * 限流过滤器
 */
@Component
public class RateLimitFilter extends ZuulFilter
{
    /**
     * 令牌桶算法
     * 令牌桶插件，每秒放置100个令牌
     */
    public static final RateLimiter rateLimiter = RateLimiter.create(100);

    /**
     * 设置过滤器的类型
     */
    public String filterType()
    {
        return PRE_TYPE;
    }

    /**
     * 设置过滤器的顺序，数字越小优先级越高
     */
    public int filterOrder()
    {
        return SERVLET_DETECTION_FILTER_ORDER - 1;
    }

    public boolean shouldFilter()
    {
        return true;
    }

    public Object run()
        throws ZuulException
    {
        /**
         * 去取一个令牌，如果没有取到
         * */
        if (!rateLimiter.tryAcquire())
        {
            /**
             * 可以设置权限，也可以抛出异常
             * */
            throw new RateLimitException();
        }
        return null;
    }
}
